import { Component, OnInit, Input, Output, EventEmitter, OnChanges, OnDestroy, SimpleChanges } from '@angular/core';
import { formatDate } from '@angular/common';

import { NzMessageService } from 'ng-zorro-antd/message';

import { CommonService } from '../../../core';

@Component({
  selector: 'app-list-result-panel',
  templateUrl: './list-result-panel.component.html',
  styleUrls: ['./list-result-panel.component.scss']
})
export class ListResultPanelComponent implements OnInit, OnChanges, OnDestroy {
  @Input() TableData = null;
  // 是否开启删除？
  deleItem = false;
  select = -1;
  // 昨天
  yesterday = null;
  @Input() totalRecord = 0;
  @Output() listclick = new EventEmitter<any>();
  // 更新页面信息
  @Output() updateList = new EventEmitter<any>();
  waitDelete = [];

  subscriptions = [];

  constructor(
    private commonService: CommonService,
    private message: NzMessageService
  ) { }

  ngOnInit() {
    // 获取24小时内的日期
    this.getIn24Hour();
    this.subscriptions.push(
      postal.channel('QUESTION-MARK').subscribe('question-mark', res => {
        this.select = -1;
      })
    );
  }
  flyTo(e, i) {
    this.select = i;
    this.listclick.emit(e);
    // 将信息公布给界面组件把
    postal.channel('QUESTION-MARK').publish('hl-question-mark', e);
  }
  ngOnChanges(changes: SimpleChanges) {
    if (changes.TableData && changes.TableData.currentValue) {
      this.TableData = changes.TableData.currentValue;
      // TODO: 将所有的数据按创建时间进行排序(最后创建的在上面)
      this.TableData.sort(function (a, b) {
        return a.properties.createtime < b.properties.createtime ? 1 : -1;
      });
    }
  }

  // checkboxchanges改变的时候
  checksChange(e) {
    this.waitDelete = e;
  }
  // 删除
  openDel() {
    // 开启批量删除状态
    this.deleItem = true;
  }
  // 删除item项
  deleteItems() {
    if (this.waitDelete.length === 0) {
      // 关闭批量删除状态
      this.deleItem = false;
      return;
    }
    const ids = _.join(this.waitDelete, ',');
    const params = { remarkIds: ids };
    this.commonService.delQuestionMark(params).subscribe(res => {
      if (res.code === 1 && res.data) {
        // 更新页码信息（告诉父组件，需要更新）
        this.updateList.emit(true);
        // 提示用户内容更新完成！
        this.message.info('删除成功！');
        postal.channel('QUESTION_TREE_CHANNEL').publish('refrese');
      } else {
        this.message.info('删除失败！');
      }
    });
    // 关闭批量删除状态
    this.deleItem = false;
  }

  cancel() {
    // 取消删除
    this.deleItem = false;
  }

  // 封装一个data函数: 日期相减小于24小时的设置为true，否则为false
  getIn24Hour() {
    const date = new Date().setDate(new Date().getDate() - 1);
    const currentdate = formatDate(date, 'yyyy-MM-dd hh:mm:ss', 'en-US');
    // 获取比当前时间小一天的时间，然后拿这个时间和现有时间进行比较，return false or true;
    this.yesterday = currentdate;
  }


  ngOnDestroy() {
    this.subscriptions.forEach(element => {
      element.unsubscribe();
    });
  }

}
